package com.kdtech.analyse.outside;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.kdtech.analyse.AnalyseNews;
import com.kdtech.analyse.JSoupUtils;
import com.kdtech.analyse.Bbs.common.BbsAnalyseDiscuz;
import com.kdtech.crawler.CrawlHTML;

import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.HtmlCleaner;
import com.kdtech.utils.RegexUtils;
import com.kdtech.utils.StringUtils;

/**
 * @author KK
 *
 */
public class BackchinaNewsAnalyse<AbstractMeta> implements AnalyseNews {

	private static final String[] regex={
		"http://www.backchina.com/news/.*/[0-9]{5,}.html",
		"http://www.backchina.com/forum/.*/info-[0-9]*-1-1.html",
		"http://www.backchina.com/blog/.*/article-[0-9]*.html",
		"http://www.backchina.com/forum.php\\?extra=&mod=viewthread&tid=[0-9]*",
		"http://www.backchina.com/forum.php\\?extra=page%3D1&mod=viewthread&tid=[0-9]*",

	};


	
	public boolean isDetailPage(String url) {
		return RegexUtils.matchAnyIgnoreCase(url, regex);
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		NewsMeta news=new NewsMeta();
		if (urlMeta.getHtml() == null) {
		}
		String htmltxt=urlMeta.getHtml();
		String url=urlMeta.getUrl();

		news.setUrl(url);
		String title=null;
		String content=null;
		String author=null;
		Long date=null;
		Document doc=Jsoup.parse(htmltxt);
		if (url.startsWith("http://www.backchina.com/forum")){
			return new BbsAnalyseDiscuz().parserHtml(urlMeta);
		}else

		if (url.startsWith("http://www.backchina.com/news")){
			title =doc.select("h1").text();
			date=DateUtils.matchDate(doc.select(".xg1").text());
			author=JSoupUtils.matchAuthor(doc, "来源:");

			content=HtmlCleaner.getContentHtml(url,doc.select(".main_content"));
		}
		else if (url.startsWith("http://www.backchina.com/blog")){
			title =doc.select("h1").text();
			date=JSoupUtils.matchDate(doc, "作者:");
			author=JSoupUtils.matchAuthor(doc, "作者:");
			doc.select("#blog_article ul").remove();
			content=HtmlCleaner.getContentHtml(url,doc.select("#blog_article"));
		}

		news.setTitle(StringUtils.trimSpace(title));
		news.setContent(content);
		news.setAuthor(author);
		news.setDate(date);

		return news;
	}
	
	public com.kdtech.entity.data.AbstractMeta Update(
			com.kdtech.entity.data.AbstractMeta meta) {
		return null;
	}


	public boolean isNeedUpdate() {
		// TODO Auto-generated method stub
		return false;
	}
}
